<!-- 表格组件 -->
<script lang="tsx" setup>
import {
	whManagerBsTbParkGridGetListUsingPost,
	whManagerBsTbParkGridPatrolTmpSaveOrUpdateUsingPost,
	whManagerSystemSystemUserListPageUsingPost,
} from "@/genapi/wh";
import { useAsync } from "@/hooks/use-async";
import type { FormRules } from "element-plus";
import VisionBox from "@/components/vision-box/vision-box.vue";
import * as Cesium from "cesium";
import { useUserStore } from "@/stores/user";
import { injectState } from "../state";
import dayjs from "dayjs";
import bus from "vue3-eventbus";

defineOptions({ name: "TeamDetails" });
const { page } = injectState()!;

const userStore = useUserStore();

const dialogRef = shallowRef<InstanceType<GlobalComponents["PromiseDialog"]>>();
const formDescRef = shallowRef<InstanceType<GlobalComponents["FormDesc"]>>();

const type = ref<"write" | "read">();

const isDisabled = ref(true);
let timedata = ref([])
const trigger = async (_type: "write" | "read" = "read", value = {} as any) => {
	clearEntities();
	type.value = _type;
	model.value = JSON.parse(JSON.stringify(value)) as any;
  // console.log('model',model.value)
	if (model.value.id) {
		isDisabled.value = true;
		// options1.value = model.value.patrolFrequencyList
		// 	? model.value.patrolFrequencyList.map((item) => item.split("-"))
		// 	: [{ frequency: "" }];
    options1.value = model.value.patrolFrequency
			? model.value.patrolFrequency.split(",")
			: [{ frequency: "" }];
		tempEntities.value = JSON.parse(model.value.patrolRoute);
		model.value.teamLeaderId = model.value.teamLeader.userId;
		model.value.userIdList = model.value.userList.map((item) => item.userId);
		drawTempEntities();
	} else {
		isDisabled.value = false;
		options1.value = [
			{
				frequency: "",
			},
		];
	}
  // console.log('options1',options1.value)
  timedata.value = []
  for(let i = 0; i<options1.value.length; i++){
    let res = options1.value[i].split('-')
    timedata.value.push(res)
  }
	await dialogRef.value?.open();
};

defineExpose({
	trigger,
});
const model = ref<(typeof page.records.value)[0]>({});

const { execute, isLoading } = useAsync(async () => {
	model.value.patrolFrequencyList = options1.value[0].frequency
		? options1.value.map((item) => item.frequency.join("-"))
		: [];
	await formDescRef.value?.formRef?.validate();
	await ElMessageBox.confirm("确认提交？", "提示", {
		type: "warning",
	});
	await whManagerBsTbParkGridPatrolTmpSaveOrUpdateUsingPost({
		data: {
			...model.value,
			patrolRoute: JSON.stringify(tempEntities.value),
		},
	});
	model.value;
	ElMessage.success("提交成功");
	trigger("write");
	isDisabled.value = true;
  bus.emit('updateTeamList')
	page.execute();
	dialogRef.value?.complete();
});

interface RuleForm {
	examContent: string;
	examType: string;
	examSelect: string;
	examAnswer: string;
	workerType: string;
}

const rules = reactive<FormRules<RuleForm>>({
	examContent: [{ required: true, message: "请输入", trigger: "blur" }],
	examType: [{ required: true, message: "请输入", trigger: "blur" }],
	examSelect: [{ required: true, message: "请输入", trigger: "blur" }],
	examAnswer: [{ required: true, message: "请输入", trigger: "blur" }],
	workerType: [{ required: true, message: "请选择", trigger: "blur" }],
});

const multiAnswer = ref([]);

watch(multiAnswer, (val) => {
	model.value.examAnswer = val.sort().join(",");
});

const options1 = ref([
	{
		frequency: "",
	},
]);

const addOption1 = () => {
	options1.value.push({
		frequency: "",
	});
};

const removeOption1 = () => {
	options1.value = options1.value.slice(0, options1.value.length - 1);
};

const tempEntities = ref([]);

const createRoute = () => {
	let handler = new Cesium.ScreenSpaceEventHandler(
		userStore.viewer.scene.canvas,
	);
	let position = [];
	//鼠标移动事件
	handler.setInputAction(function (
		movement,
	) {}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	//左键点击操作
	handler.setInputAction(function (click) {
		//调用获取位置信息的接口
		let ray = userStore.viewer.camera.getPickRay(click.position);
		position = userStore.viewer.scene.globe.pick(ray, userStore.viewer.scene);
		tempEntities.value.push(position);
		let tempLength = tempEntities.value.length;
		//调用绘制点的接口
		drawPoint(tempEntities.value[tempEntities.value.length - 1]);
		// tempEntities.value.push(point);
		if (tempLength > 1) {
			let pointline = drawPolyline([
				tempEntities.value[tempEntities.value.length - 2],
				tempEntities.value[tempEntities.value.length - 1],
			]);
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	//右键点击操作
	handler.setInputAction(function (click) {
		tempPoints = [];
		handler.destroy(); //关闭事件句柄
		handler = null;
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

const drawTempEntities = () => {
	if (tempEntities.value.length < 0) {
		return;
	}
	for (let i = 0; i < tempEntities.value.length - 1; i++) {
		drawPolyline([tempEntities.value[i], tempEntities.value[i + 1]]);
	}
	tempEntities.value.forEach((item) => {
		drawPoint(item);
	});
};

const drawPoint = (position, config) => {
	let viewer = userStore.viewer;
	let config_ = config ? config : {};
	return viewer.entities.add({
		name: "点几何对象",
		position: position,
		point: {
			color: Cesium.Color.SKYBLUE,
			pixelSize: 10,
			outlineColor: Cesium.Color.YELLOW,
			outlineWidth: 3,
			disableDepthTestDistance: Number.POSITIVE_INFINITY,
			heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
		},
	});
};

const drawPolyline = (positions, config_) => {
	let viewer = userStore.viewer;
	if (positions.length < 1) return;
	let config = config_ ? config_ : {};
	return viewer.entities.add({
		name: "线几何对象",
		polyline: {
			positions: positions,
			width: config.width ? config.width : 5.0,
			material: new Cesium.PolylineGlowMaterialProperty({
				color: config.color
					? new Cesium.Color.fromCssColorString(config.color)
					: Cesium.Color.GOLD,
			}),
			depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
				color: config.color
					? new Cesium.Color.fromCssColorString(config.color)
					: Cesium.Color.GOLD,
			}),
			clampToGround: true,
		},
	});
};

const clearEntities = () => {
	let viewer = userStore.viewer;
	tempEntities.value = [];
	// 清除之前的实体
	const entitys = viewer.entities._entities._array;
	let length = entitys.length;
	// 倒叙遍历防止实体减少之后entitys[f]不存在
	for (let f = length - 1; f >= 0; f--) {
		if (
			entitys[f]._name &&
			(entitys[f]._name === "点几何对象" ||
				entitys[f]._name === "线几何对象" ||
				entitys[f]._name === "面几何对象")
		) {
			viewer.entities.remove(entitys[f]);
		}
	}
};

const gridList = ref([]);

const getGridList = async () => {
	const { data } = await whManagerBsTbParkGridGetListUsingPost({ data: {} });
	gridList.value =
		data?.map((item) => ({ label: item.name, value: item.id })) ?? [];
};

const userList = ref([]);

const getUserList = async () => {
	const { data } = await whManagerSystemSystemUserListPageUsingPost({
		data: {
			current: 1,
			size: 9999,
		},
	});
	userList.value =
		data?.records.map((item) => ({ label: item.nickName, value: item.id })) ??
		[];
};

onMounted(() => {
	getGridList();
	getUserList();
});

const edti = async() => {
  isDisabled.value = false
  options1.value = [
    {
      frequency: "",
    }
  ]
}
</script>

<template>
	<div class="teamDetails">
		<div class="teamDetailsTitle">
			<span>基本信息</span>
			<div class="btnBox">
				<el-button @click="edti" :disabled="!isDisabled"
					>编辑</el-button
				>
				<el-button type="primary" @click="execute" :disabled="isDisabled"
					>保存</el-button
				>
			</div>
		</div>
		<div class="teamDetailsForm">
			<el-scrollbar>
				<el-form
					ref="FormDesc"
					:rules="rules"
					:model="model"
					label-position="top"
				>
					<el-row>
						<el-col :span="11">
							<el-form-item label="队伍名称" prop="teamName">
								<el-input
									v-model="model.teamName"
									placeholder="请输入队伍名称"
									:disabled="isDisabled"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="负责片区" prop="gridId">
								<el-select-v2
									class="w-100%"
									:disabled="isDisabled"
									:options="gridList"
									v-model="model.gridId"
									placeholder="请选择网格"
								></el-select-v2>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="11">
							<el-form-item label="队长姓名" prop="teamLeaderId">
								<el-select-v2
									class="w-100%"
									:disabled="isDisabled"
									:options="userList"
									v-model="model.teamLeaderId"
									placeholder="请选择人员"
								></el-select-v2>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="队长联系电话" prop="teamLeaderPhone">
								<el-input
									v-model="model.teamLeaderPhone"
									placeholder="请输入联系电话"
									:disabled="isDisabled"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
							<el-form-item label="队伍成员" prop="userIdList">
								<el-select-v2
									class="w-100%"
									multiple
									collapse-tags
									collapse-tags-tooltip
									:max-collapse-tags="10"
									:disabled="isDisabled"
									:options="userList"
									v-model="model.userIdList"
									placeholder="请选择人员"
								></el-select-v2>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
							<el-form-item label="巡查任务" prop="patrolTask">
								<el-input
									type="textarea"
									v-model="model.patrolTask"
									placeholder="请输入巡查任务"
									:disabled="isDisabled"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
              <!-- 编辑巡查频率 -->
              <el-form-item label="巡查频率" prop="patrolFrequency" v-if="!isDisabled">
								<div
									class="frequencyItem"
									style="width: 49%; margin-bottom: 5px"
									v-for="(item, i) in options1"
									:key="i"
								>
									<el-time-picker
										v-model="item.frequency"
										style="width: calc(100% - 70px)"
										is-range
										value-format="HH:mm"
										range-separator="到"
										start-placeholder="起始时间"
										end-placeholder="结束时间"
									/>
									<el-button
										text
										p="x-4px!"
										un-text="16px! #52DB68!"
										@click="addOption1"
										v-if="i === options1.length - 1"
									>
										<el-icon class="i-material-symbols:add-circle-rounded" />
									</el-button>
									<el-button
										text
										p="x-4px!"
										un-text="16px! #CE0505!"
										@click="removeOption1"
										v-if="i === options1.length - 1 && i !== 0"
									>
										<el-icon
											class="i-material-symbols:do-not-disturb-on-rounded"
										/>
									</el-button>
								</div>
							</el-form-item>
              <!-- 回显时间 -->
							<el-form-item label="巡查频率" prop="patrolFrequency" v-else>
								<div
									class="frequencyItem"
									style="width: 49%; margin-bottom: 5px"
									v-for="(item, i) in timedata"
									:key="i"
								>
									<el-time-picker
										v-model="timedata[i]"
										style="width: calc(100% - 70px)"
										:disabled="isDisabled"
										is-range
										value-format="HH:mm"
										range-separator="到"
										start-placeholder="起始时间"
										end-placeholder="结束时间"
									/>
									<el-button
										text
										p="x-4px!"
										un-text="16px! #52DB68!"
										@click="addOption1"
										v-if="i === options1.length - 1"
									>
										<el-icon class="i-material-symbols:add-circle-rounded" />
									</el-button>
									<el-button
										text
										p="x-4px!"
										un-text="16px! #CE0505!"
										@click="removeOption1"
										v-if="i === options1.length - 1 && i !== 0"
									>
										<el-icon
											class="i-material-symbols:do-not-disturb-on-rounded"
										/>
									</el-button>
								</div>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div class="visionBoxContainer">
					<div class="editBtnBox" v-show="!isDisabled">
						<el-button type="primary" @click="createRoute">
							<template #icon>
								<el-icon class="i-custom:edit" />
							</template>
							绘制
						</el-button>
						<el-button type="primary" @click="clearEntities">
							<template #icon>
								<el-icon class="i-custom:delete" />
							</template>
							清空
						</el-button>
					</div>

					<VisionBox />
				</div>
			</el-scrollbar>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.teamDetails {
	height: 100%;
	width: 72%;
	display: flex;
	flex-direction: column;
	padding: 0 30px;
	.teamDetailsTitle {
		height: 40px;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-weight: 600;
	}
	.teamDetailsForm {
		width: 100%;
		height: calc(100% - 40px);
		display: flex;
		flex-direction: column;
		overflow-y: auto;
	}
	.visionBoxContainer {
		width: 100%;
		height: 500px;
		position: relative;
		.editBtnBox {
			position: absolute;
			top: 5px;
			right: 5px;
			z-index: 999;
		}
	}
	.el-row {
		justify-content: space-between;
	}
}
</style>
